var app = getApp();


var isLimitBuy = false;  //是否限购
var limitBuyNum = 0;
var showaddress = true; //是否显示地址
var common = require("../../utils/Conmon.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    IsPointDeductible: false,
    index: 0,
    array: ['不限收货时间', '只限工作日收货', '只限双休日收货'],
    cartList: [],
    cneeId: 0,
    list: [],
    freightMoney: '免邮',
    cartMoney: 0,
    addr: null,
    remark: "",
    remarkList: [],
    pointName: "",
    deductiblePoint: 0, //可抵扣总积分
    bili: 0,
    totalIntegral: "",
    totalCommission: "",
    showCartMoney: '0.00',
    showmap: false,
    showAddress: true,
    buyNum: 0,
    selfextraclist: null,
    selectshopid: -1, //当前正在选择自提地址的店铺
    latitude: 0,
    longitude: 0,
    logistics: ["物流配送", "到点自提"],
    logisticsIndex: 0
  },
  //显示选择自提点
  showChangeSelfExteac: function(e) {
    var shopId = e.currentTarget.dataset.shopid;
    var list = this.data.list;
    var selfextraclist;

    for (var i = 0, lenI = list.length; i < lenI; ++i) {
      if (list[i].ShopId == shopId) {
        selfextraclist = list[i].SelfExtracList;
        var id = list[i].SelectSelfExtracId;
        for (var j = 0, lenj = selfextraclist.length; j < lenj; ++j) {
          if (selfextraclist[j].ID == id) {
            selfextraclist[j].checked = true;
          } else {
            selfextraclist[j].checked = false;
          }
        }
        break;
      }
    }
    this.setData({
      list: list,
      showmap: true,
      selfextraclist: selfextraclist,
      selectshopid: shopId
    });
  },
  //改变自提点
  changeSelfExteac: function(e) {
    var shopid = this.data.selectshopid;
    var list = this.data.list,
      selfextraclist = this.data.selfextraclist,
      id = e.detail.value;
    for (var j = 0, lenJ = selfextraclist.length; j < lenJ; ++j) {
      if (selfextraclist[j].ID == id) {
        selfextraclist[j].checked = true;
        for (var i = 0, lenI = list.length; i < lenI; ++i) {
          if (list[i].ShopId == shopid) {
            list[i].SelectSelfExtracId = id;
            list[i].SelectSelfExtracName = selfextraclist[j].ShopName;
            list[i].SelectSelfExtracAddress = selfextraclist[j].ShopAddress;
            list[i].ShowSelfExtrac = true;
            break;
          }
        }
        break;
      }
    }

    this.setData({
      list: list,
      selfextraclist: selfextraclist,
      showmap: !this.data.showmap
    });
  },

  getmap: function(e) {
    var la = e.currentTarget.dataset.la;
    var lo = e.currentTarget.dataset.lo;
    var name = e.currentTarget.dataset.name;
    // wx.navigateTo({
    //   url: '/pages/map/map?latitude=' + la + '&longitude=' + lo + '&name=' + name,
    // });
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function(res) {
        var latitude = res.latitude
        var longitude = res.longitude
        wx.openLocation({
          latitude: parseFloat(la),
          longitude: parseFloat(lo),
          name: name,
          scale: 28
        })
      }
    })
  },
  hidemap: function() {
    this.setData({
      showmap: false
    })
  },
  bindPickerChange: function(e) {
    this.setData({
      index: e.detail.value
    })
  },
  bindlogisticsChange: function(e) {
    this.setData({
      logisticsIndex: e.detail.value
    });
    if (e.detail.value == 1) {
      var shopId = e.target.dataset.shopid;
      var list = this.data.list,
        ischeck = e.detail.value;
      var showmap = false;
      var selfextraclist;
      var selectednum = 0;
      var logisticsnum = 0;
      var that = this;
      var final = 0;

      for (var i = 0, lenI = list.length; i < lenI; ++i) {
        if (list[i].ShopId == shopId) {
          selfextraclist = list[i].SelfExtracList;
          list[i].pickchecked = ischeck;
          if (ischeck == 1) {
            if (selfextraclist != null && selfextraclist.length > 0) {
              for (var k = 0, lenK = selfextraclist.length; k < lenK; ++k) {
                var la = selfextraclist[k].Latitude;
                var lo = selfextraclist[k].Longitude;
                var distance = getDistance(this.data.latitude, this.data.longitude, la, lo);
                selfextraclist[k].distance = distance;
                selfextraclist[k].distanceKm = (distance / 1000).toFixed(2);
              }

              selfextraclist.sort(function(a, b) {
                var ai = parseInt(a.distance);
                var bi = parseInt(b.distance);
                if (ai > bi) {
                  return 1;
                } else if (ai < bi) {
                  return -1;
                } else {
                  return 0;
                }
              });
            }
            list[i].pickmsg = '（开启自提后，将不提供配送）';
            showmap = true;
            list[i].showCartMoney = parseFloat((list[i].CartMoney - list[i].FreightAmount).toFixed(2));
            if (list[i].checked) {
              dikou(shopId, list, list[i].checked, that);
            }
          } else {
            list[i].pickmsg = '';
            list[i].ShowSelfExtrac = false;
            if (list[i].checked) {
              dikou(shopId, list, list[i].checked, that);
            } else {
              list[i].showCartMoney = list[i].CartMoney;
            }
          }
        }
        if (list[i].pickchecked) {
          selectednum++;
        }
        if (list[i].IsLogistics) {
          logisticsnum++;
        }
        final += list[i].showCartMoney;
      }

      showaddress = false;


      this.setData({
        list: list,
        showmap: showmap,
        selfextraclist: selfextraclist,
        selectshopid: shopId,
        showAddress: showaddress,
        showCartMoney: final,
      });
    } else {
      this.setData({
        showAddress: true
      });
    }

  },
  //备注
  bindRemark: function (e) {
    var rlist = this.data.remarkList;
    var content = e.detail.value;
    var shopId = e.target.dataset.shopid;
    for (var i = 0, len = rlist.length; i < len; i++) {
      if (rlist[i].ShopId == shopId) {
        rlist[i].Remark = content;
      }
    }
    this.setData({
      remarkList: rlist
    });
  },
  //抵扣积分计算
  deductibleCalculate: function(e) {
    var shopId = e.target.dataset.shopid;
    var list = this.data.list;
    var selfck = e.detail.value; //自己的状态
    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].ShopId == shopId) {
        list[i].checked = selfck;
        break;
      }
    }

    var that = this;
    dikou(shopId, list, selfck, that);
  },
  //下单
  goSubmit: function(e) {
    var that = this;
    var showAddress = that.data.showAddress;

    //执行登陆注册设置逻辑

    common.GetAuthorLoginPage(123);
    common.GetLoginBindPhone(123);

    if (isLimitBuy) {
      wx.showModal({
        content: '该商品限购' + limitBuyNum + '件',
        showCancel: false,
        confirmText: "确定"
      });
      return;
    }
    if (that.data.cneeId == 0 || that.data.cneeId == undefined) {
      if (showAddress) {
        wx.showModal({
          content: "请选择收货地址",
          showCancel: false,
          confirmText: "确定"
        });
        return;
      }
    }
    //抵扣
    var list = that.data.list;
    var deductiblelist = [];
    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].checked) {
        var deductible = {};
        deductible.ShopId = list[i].ShopId;
        deductible.Index = list[i].indexnum;
        deductiblelist.push(deductible);
      }
    }
    //自提地址
    var pickedlist = [];
    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].pickchecked) {
        var picked = {};
        picked.ShopId = list[i].ShopId;
        picked.SelfExtracId = list[i].SelectSelfExtracId;
        pickedlist.push(picked);
      }
    }

    if (!pickedlist.length > 0 && showAddress == false) {
      wx.showModal({
        content: "请选择自提地址",
        showCancel: false,
        confirmText: "确定"
      });
      return;
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    var data = {
      CustId: app.globalData.custID,
      UserId: wx.getStorageSync('UserInfo').UserID,
      CneeId: that.data.cneeId,
    
      Product: that.data.product,
      PostKind: that.data.index,
      Type : "teambuying",
      RemarkList: that.data.remarkList,
      SelectCartList: that.data.cartList,
      DeductibleList: deductiblelist,
      PostKind: that.data.index,
      PickedUpList: pickedlist
    };
    wx.request({
      url: app.globalData.apiurl + '/mobile/api/OrderForm/OrderWechat',
      data: JSON.stringify(data),
      method: 'POST',
      header: {
        'X_ManuName': app.globalData.manuName
      },
      success: function(res) {
        wx.hideLoading();
        if (res.data.code == 1200) {
          var orderId = res.data.content.OrderID;
          var payno = res.data.content.PayNo;
          //清除缓存
          wx.removeStorageSync('Winmobi4MallTeamBuyProduct');
          wx.redirectTo({
            url: '/pages/teamSubmitOrder2/teamSubmitOrder2?PayNo=' + payno + '&OrderId=' + orderId,
          })
        } else if (res.data.code == 200) {
          wx.removeStorageSync('Winmobi4MallTeamBuyProduct');
          var orderid = res.data.content.OrderID;
          var UnionStoreId = res.data.content.UnionStoreId;
          var TeamId = res.data.content.TeamId;
          wx.showModal({
            content: '支付成功',
            showCancel: false,
            confirmText: "确定",
            success: function(res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/payment/payment?custId=' + app.globalData.custID + '&unionStoreID=' + UnionStoreId + '&teamId=' + TeamId + '&orderId=' + orderid,
                });
              }
            }
          });
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            confirmText: "确定"
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //获取缓存的购物车选中项
    var Product = wx.getStorageSync('Winmobi4MallTeamBuyProduct');
    if (Product) {
      this.setData({
        cartList: JSON.parse(Product)
      });
    } else {
      wx.showModal({
        content: "请先选择要购买的商品",
        showCancel: false,
        confirmText: "确定",
        complete: function() {
          wx.navigateTo({
            url: '/pages/goodsList/goodsList',
          })
        }
      })
      return;
    }
    var cneeid = options.CneeID;
    if (cneeid) {
      this.setData({
        cneeId: options.CneeID
    
      });
    }
    //加载数据
    loadCartProduct(this);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})

function loadCartProduct(that) {
  if (that.data.cartList == null || that.data.cartList.length <= 0) {
    wx.showModal({
      content: "请先选择要购买的商品",
      showCancel: false,
      confirmText: "确定",
      complete: function() {
        wx.switchTab({
          url: '/pages/cart/cart'
        })
      }
    });
    return;
  }

  wx.showLoading({
    title: '加载中...',
    mask: true
  });
  var data = {
    CustId: app.globalData.custID,
    UserId: wx.getStorageSync('UserInfo').UserID,
    SelectCartList: that.data.cartList,
    CneeId: that.data.cneeId,
    Source: "teambuying"
  };
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/OrderForm/GetSelectCartProductListWechat',
    data: JSON.stringify(data),
    method: 'POST',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {
      wx.hideLoading();
      if (res.data.code == 1200) {
        var result = res.data.content;
        console.log(result);
        var cnee = result.CneeAddress;
        if (cnee) {
          that.setData({
            cneeId: cnee.CneeID
          });
        }
        var rlist = [];
        if (result.UnionCartProducts) {
          for (var i = 0, len = result.UnionCartProducts.length; i < len; i++) {
            var shop = {};
            shop.ShopId = result.UnionCartProducts[i].ShopId;
            shop.Remark = "";
            rlist.push(shop);

            result.UnionCartProducts[i].checked = false;
            result.UnionCartProducts[i].indexnum = 0;
            result.UnionCartProducts[i].dikou = 0;
            result.UnionCartProducts[i].deductibleMoney = 0;
            result.UnionCartProducts[i].showCartMoney = result.UnionCartProducts[i].CartMoney;

            if (result.UnionCartProducts[i].CartProducts != null && result.UnionCartProducts[i].CartProducts.length > 0) {
              for (var j = 0; j < result.UnionCartProducts[i].CartProducts.length; j++) {
                if (result.UnionCartProducts[i].CartProducts[j].ActivityType != 8 && !isLimitBuy) {
                  if (result.UnionCartProducts[i].CartProducts[j].IsLimitBuy && (result.UnionCartProducts[i].CartProducts[j].BuyNum > result.UnionCartProducts[i].CartProducts[j].LimitBuyNum)) {
                    isLimitBuy = result.UnionCartProducts[i].CartProducts[j].IsLimitBuy;
                    limitBuyNum = result.UnionCartProducts[i].CartProducts[j].LimitBuyNum;
                  }

                }
              }
            }
          }
        }
        that.setData({
          IsPointDeductible: result.IsPointDeductible,
          list: result.UnionCartProducts,
          cartMoney: result.CartMoney.toFixed(2),
          addr: result.CneeAddress,
          remarkList: rlist,
          pointName: result.PointName,
          deductiblePoint: parseFloat(result.DeductiblePoint),
          bili: parseFloat(result.Bili),
          totalIntegral: result.TotalIntegral,
          totalCommission: result.TotalCommission,
          showCartMoney: result.CartMoney.toFixed(2),
          showAddress: result.IsShowAddress,
          buyNum: result.PayNum,
        });
      } else {
        console.log('加载失败');
      }
    }
  })
}

//抵扣
function dikou(shopId, list, selfck, that) {
  var sumMoney = parseFloat(that.data.cartMoney);
  var remainPoint = that.data.deductiblePoint;
  var bili = that.data.bili;
  var maxindex = 1;
  for (var i = 0, len = list.length; i < len; i++) {
    var dikou = 0;
    var cartMoney = list[i].CartMoney;
    if (list[i].pickchecked && list[i].FreightAmount > 0) {
      cartMoney = parseFloat((list[i].CartMoney - list[i].FreightAmount).toFixed(2));
    }
    if (!selfck || list[i].ShopId != shopId) {
      if (list[i].checked) {
        if (cartMoney > 0 && remainPoint > 0) {
          var re = remainPoint - cartMoney;
          if (re > 0) {
            dikou = cartMoney;
            cartMoney = 0;
            remainPoint = re;
          } else {
            dikou = remainPoint;
            cartMoney = cartMoney - remainPoint;
            remainPoint = 0;
          }
          list[i].checked = true;
          list[i].indexnum = maxindex;
          maxindex = maxindex + 1;
        } else {
          list[i].checked = false;
          list[i].indexnum = 0;
        }
      } else {
        dikou = 0;
        list[i].checked = false;
        list[i].indexnum = 0;
      }
      list[i].showCartMoney = cartMoney;
      list[i].dikou = dikou * bili;
      list[i].deductibleMoney = dikou;
    }
  }

  for (var i = 0, len = list.length; i < len; i++) {
    if (list[i].ShopId == shopId && list[i].checked) {
      var dikou = 0;
      var cartMoney = list[i].CartMoney;
      if (list[i].pickchecked && list[i].FreightAmount > 0) {
        cartMoney = parseFloat((list[i].CartMoney - list[i].FreightAmount).toFixed(2));
      }
      if (cartMoney > 0 && remainPoint > 0) {
        var re = remainPoint - cartMoney;
        if (re > 0) {
          dikou = cartMoney;
          cartMoney = 0;
          remainPoint = re;
        } else {
          dikou = remainPoint;
          cartMoney = cartMoney - remainPoint;
          remainPoint = 0;
        }
        list[i].indexnum = maxindex;
        list[i].checked = true;
      } else {
        list[i].indexnum = 0;
        list[i].checked = false;
        wx.showModal({
          content: "已达到最大抵扣金额",
          showCancel: false,
          confirmText: "确定"
        })
      }
      list[i].showCartMoney = cartMoney;
      list[i].dikou = dikou * bili;
      list[i].deductibleMoney = dikou;
      break;
    }
  }

  var final = 0;
  for (var i = 0, len = list.length; i < len; i++) {
    final += list[i].showCartMoney;
  }
  that.setData({
    list: list,
    showCartMoney: final
  });
}

//计算两点之间的距离
function getDistance(lat1, lng1, lat2, lng2) {
  lat1 = lat1 || 0;
  lng1 = lng1 || 0;
  lat2 = lat2 || 0;
  lng2 = lng2 || 0;

  var rad1 = lat1 * Math.PI / 180.0;
  var rad2 = lat2 * Math.PI / 180.0;
  var a = rad1 - rad2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;

  var r = 6378137;
  var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));

  return distance;
}

function sortNumber(a, b) {
  return a - b
}